import DB

__doc__ = """\
ChomsPy.DAD
ChomsPy Data Acquisition Device

description:
	Pragmatic Interface Modules to ChomsPy DB.
	
usage:
	DAD.Connect(conf, user, password)
		conf = Dictionary with Configuration Options
		user = User name
		password = User password
		
	DAD.Command(pragmatic[, data])
		pragmatic = String with Pragmatic Command
		data = Dictionary with Data Object (optional)
		
example:
	import Modules.ChomsPy.DAD as DAD
	import Modules.Pygmund.Id as Id
	conf = Id.Init("id/cognition.conf").Get("CHOMSPY")
	db = DAD.Connect(conf, "admin", "drowssap")
	r = db.Command("Journal.Entries/Get/entry.2010,12,10,203420")
	print r
	
"""

class Connect:
	def __init__(self, conf, user, password):
		# Delimiters: [0] = subject/object delimiter, [1] = modifier delimiter
		self.delimiters = conf["delimiters"]
		self.dbroot = conf["dbroot"]
		self.grammar = conf["grammar"]
		self.validate = conf["validate-objects"]
		self._DB = DB.Init(conf, user, password, True)
		
	def Command(self, pragmatic, data=False):
		pragmatic = self._ProcessPragmatic(pragmatic)
		
		if "error" in pragmatic:
			return pragmatic
		
		if pragmatic["verb"] == "Get":
			return self._DB.Get(pragmatic["subject"], pragmatic["object"])
			
		elif pragmatic["verb"] == "Set":
			return self._DB.Set(pragmatic["subject"], pragmatic["object"], data)
			
		elif pragmatic["verb"] == "List":
			return self._DB.List(pragmatic["subject"], pragmatic["object"])
			
		elif pragmatic["verb"] == "Remove":
			return self._DB.Remove(pragmatic["subject"], pragmatic["object"])
			
		else:
			# Error
			return { "error" : 71, "message" : "Invalid Verb in Pragmatic.", "data" : pragmatic }
	
	def _ProcessPragmatic(self, pragmatic):
		p = pragmatic.split("/")
		if len(p) < 3:
			return { "error" : 76, "message" : "Invalid Pragmatic format (missing parameter)", "data" : pragmatic }
		
		if self.grammar == "svo":
			s, v, o = p
		elif self.grammar == "sov":
			s, o, v = p
		elif self.grammar == "vso":
			v, s, o = p
		elif self.grammar == "vos":
			v, o, s = p
		else:
			return { "error" : 87, "message" : "Invalid grammar format.", "data" : [ pragmatic, self.grammar ] }
		
		subj = {}
		s = s.split(self.delimiters[0])
		if len(s) < 2:
			subj["subject"] = s[0]
			subj["mods"] = []
		else:
			subj["subject"], subj["mods"] = s
			subj["mods"] = subj["mods"].split(self.delimiters[1])
		
		obj = {}
		o = o.split(self.delimiters[0])
		if len(o) < 2:
			obj["object"] = o[0]
			obj["mods"] = []
		else:
			obj["object"], obj["mods"] = o
			obj["mods"] = obj["mods"].split(self.delimiters[1])
		
		return { "subject" : subj, "object" : obj, "verb" : v }
